package edu.hrbu.spring.service.impl;

import edu.hrbu.spring.dao.ActDao;
import edu.hrbu.spring.pojo.Act;
import edu.hrbu.spring.service.ActService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author 徐登宇
 */

@Service
public class ActServiceImpl implements ActService {

    @Resource(name = "actDaoImpl")
    ActDao actDao;

    @Override
    @Transactional
    public boolean transfer(Integer fromNo, Integer toNo, Integer balance) {
        int i = 0;
        Integer fromBalance = actDao.selectByNo(fromNo);
        System.out.println("fromBalance：" + fromBalance);
        Integer toBalance = actDao.selectByNo(toNo);
        System.out.println("toBalance：" + toBalance);
        if (fromBalance <= 0 || fromBalance < balance) {
            System.err.println("余额不足");
            return false;
        }
        i += actDao.updateByNo(fromNo, fromBalance - balance);
//        int n = 1 / 0;
        i += actDao.updateByNo(toNo, toBalance + balance);
        return i == 2;
    }

    @Resource(name = "actServiceImpl2")
    private ActService actService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED) // 默认就是这种传播行为
    public boolean save(Act act) {
        int i = 0;
        boolean f = false;
        i += actDao.insert(act);

        Act act2 = new Act(4, 1000);
        try {
            f = actService.save(act2);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return f && i == 1;

    }
}
